package com.self.hctransfer.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class WordExportController {
	
public static String pt;
	
	static {
		// 获取文件地址
		pt = WordExportController.class.getResource("/").getPath();
		pt = pt + "static/doc/";
	}
	
	static class Chapter{
		int chapterNum;
		List<Section> sections;
		boolean isWritten = false;
		public int length() {
			int sum = 0;
			for(Section s:sections) {
				sum += s.length();
			}
			return sum;
		}
		
		public Chapter(int chapterNum) {
			// TODO Auto-generated constructor stub
			this.chapterNum = chapterNum;
			sections = new ArrayList<Section>();
		}
		
		public boolean isNull() {
			
			/**
			 * 当 节数 大于1 或者 条数大于一
			 */
			if(sections != null &&( sections.size() > 1 || sections.get(0).items.size() > 1 )) {
				return false;
			}
			return true;
		}
		
		@Override
		public String toString() {
			// TODO Auto-generated method stub
			if(chapterNum != 0) {
				return "第" + numberToChinese(chapterNum) + "章";
			}
			return null;
		}
		
		
	}
	
	static class Section{
		int sectionNum;
		List<ItemN> items;
		boolean isWritten = false;
		public int length() {
			return items.size() -1;
		}
		
		public Section(int sectionNum) {
			// TODO Auto-generated constructor stub
			this.sectionNum = sectionNum;
			items=new ArrayList<ItemN>();
		}
		
		public boolean isNull() {
			
			/**
			 * 当 节数 大于1 或者 条数大于一
			 */
			if(items != null &&( items.size() > 1 )) {
				return false;
			}
			return true;
		}
		
		
		@Override
		public String toString() {
			// TODO Auto-generated method stub
			if(this.sectionNum != 0) {
				return "第" + numberToChinese(this.sectionNum) + "节";
			}
			return null;
		}
	}
	
	static class ItemN{
		int itemNum;
		String info;
		Section sec;
		Chapter cha;
		
		public ItemN(int itemNum,String info,Section sec, Chapter cha) {
			// TODO Auto-generated constructor stub
			this.info = info;
			this.itemNum = itemNum;
			this.sec = sec;
			this.cha = cha;
		}
		
		@Override
		public String toString() {
			// TODO Auto-generated method stub
			return "第" + numberToChinese(itemNum) +"条 :"+ info;
		}
	}
	
	/**
	 * 处理文本返回所有章节信息
	 * @param text
	 * @return
	 */
	public static List<ItemN> textProduce(String text){
		List<ItemN> li = new ArrayList<ItemN>();
		
		
		String[] content_list = text.split("第[\\u4e00-\\u9fa5]{1,10}章 ");
        if(content_list.length == 1) {
        	content_list = text.split("第[\\u4e00-\\u9fa5]{1,10}章 ");
        }
        if(content_list.length == 1){
			content_list = text.split("第[\\u4e00-\\u9fa5]{1,10}章　");
		}
        int total=0;
        for(int i=0;i<content_list.length;i++) {
        	// 创建每个章节对象
        	if(i == 0) {
        		continue;
        	}
        	Chapter c = new Chapter(i);
        	String[] content_list_title2 = content_list[i].split("[\\s]第[\\u4e00-\\u9fa5]{1,10}节 ");
        	if(content_list_title2.length == 1) {
        		content_list_title2 = content_list[i].split("[\\s]第[\\u4e00-\\u9fa5]{1,10}节 ");
        	}
			if(content_list_title2.length == 1){
				content_list_title2 = content_list[i].split("[\\s]第[\\u4e00-\\u9fa5]{1,10}节　");
			}
//			System.out.println("节长度: "+content_list_title2.length);
        	for(int j=0;j<content_list_title2.length;j++) {
        		// 创建每个节对象
        		Section sec = new Section(j);

//        		System.out.println("===========");
//        		System.out.println(content_list_title2[j]);
//				System.out.println("===========");
        		String[] content_list_title3 = content_list_title2[j].split("[\\s]第[\\u4e00-\\u9fa5]{1,10}条 ");
        		if(content_list_title3.length == 1){
					content_list_title3 = content_list_title2[j].split("第[\\u4e00-\\u9fa5]{1,10}条　");
				}
//    			System.out.println("content_list_title3:"+content_list_title3.length);
        		for(int k=0;k<content_list_title3.length;k++) {
    				if (k != 0 ) {
    					total++;
    					// 处理 字段内容
//						String result11 = content_list_title3[k].replace("\n","" + (char)11);
    					String reg = "( HYPERLINK \"javascript:SLC\\([0-9]+,[0-9]+\\)\" )";
						String reg2 = "\\(\\u200Bjavascript:SLC\\([0-9]+,[0-9]+\\)\\u200B\\)";
						Pattern pat = Pattern.compile(reg);

						Matcher mat=pat.matcher(content_list_title3[k]);
						String repickStr = mat.replaceAll("");
						pat = Pattern.compile(reg2);
						mat = pat.matcher(repickStr);
						repickStr = mat.replaceAll("");
//						repickStr.replace("\n", "666");
//						repickStr = repickStr.replace("", "");
//						repickStr.replace("\n","666");
    					ItemN it =  new ItemN(total, repickStr,sec,c);
    					if(c.toString() != null) {
//    						System.out.println("===" + c.toString() + "===");
    					}
    					if(sec.toString() != null) {
//    						System.out.println("===" + sec.toString() + "===");
    					}
//    					System.out.println(it.toString());
    					
//    					System.out.println("======end======");
    					sec.items.add(it);
    					li.add(it);
//    					System.out.println("==========第" + numberToChinese(i)+"章" + " 第 "+ numberToChinese(j) +"节 第" + numberToChinese(total)+"条 start===================");
//	            		System.out.println(content_list_title3[k]);
//	            		System.out.println("==========第" + numberToChinese(i)+"章" + " 第 "+ numberToChinese(j) +"节 第" + numberToChinese(total)+"条 end===================");
    				}
    			}
        		c.sections.add(sec);
        	}
        }
		
		
		return li;
	}
	
	
	/**
	 * 数字转中文
	 * @param number
	 * @return
	 */
	private static String numberToChinese(int number) {
        String[] numbers = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        String[] units = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十"};
        String sign = number < 0 ? "负" : "";
        if (number < 0) {
            number = -number;
        }
        StringBuilder result = new StringBuilder(sign);
        String string = String.valueOf(number);
        int n = string.length();
        char[] numberCharArray = string.toCharArray();
        for (int i = 0; i < n; i++) {
            int digNum = n - i; // 位数
            int num = numberCharArray[i] - '0';
            if (num != 0) {
                result.append(numbers[num]).append(units[digNum - 1]);
                continue;
            }

            if (result.toString().endsWith(numbers[0])) {
                // 如果是单位所在的位数，则去除上一个0，加上单位
                if (digNum % 4 == 1) {
                    result.deleteCharAt(result.length() - 1);
                    result.append(units[digNum - 1]);
                }
            }else{
                result.append(numbers[0]);
            }
        }
        return result.toString();
    }
	
	public static int getlength(List<Chapter> ListCha) {
		int sum = 0;
		for(Chapter c:ListCha) {
			sum += c.length();
		}
		
		return sum;
	}
	
    /**
     * 生成表格
     */
    public void createTable(XWPFTable ComTable,List<ItemN> ListCha1, List<ItemN> ListCha2){

        XWPFTableRow comTableRowOne = ComTable.getRow(0);
//        System.out.println("!@@#!@#!@#@!#@!#@!");
//		System.out.println(ListCha1.toString());
//		System.out.println(ListCha2.toString());
//		System.out.println("!@@#!@#!@#@!#@!#@!");
		comTableRowOne.getCell(0).setText("原法则");

        comTableRowOne.addNewTableCell().setText("新法则");
        int max = (ListCha1.size()>ListCha2.size())?ListCha1.size():ListCha2.size();
        
        List<Section> ls1 =null;
        List<Section> ls2 =null;
        XWPFTableRow comTableRowNew = null;
        for(int i=0;i< max; i++){

        	// 确认 章是否写完
            if((i< ListCha1.size() && !ListCha1.get(i).cha.isWritten ) || (i< ListCha2.size() && !ListCha2.get(i).cha.isWritten )) {
            	comTableRowNew = ComTable.createRow();
            	if(i< ListCha1.size() && !ListCha1.get(i).cha.isWritten) {
					XWPFParagraph pIO = comTableRowNew.getCell(0).addParagraph();
					XWPFRun rIO = pIO.createRun();
					//
//					String[] al = ListCha1.get(i).cha.toString().split("\n");
//					System.out.println("al: " + al.length);
					rIO.setText(ListCha1.get(i).cha.toString());
            		ListCha1.get(i).cha.isWritten = true;
            	}
            	if(i< ListCha2.size() && !ListCha2.get(i).cha.isWritten) {
            		//
					XWPFParagraph pIO = comTableRowNew.getCell(1).addParagraph();
					XWPFRun rIO = pIO.createRun();
					rIO.setText(ListCha2.get(i).cha.toString());



//            		comTableRowNew.getCell(1).setText(ListCha2.get(i).cha.toString());
            		ListCha2.get(i).cha.isWritten = true;
            	}
            }
            
            // 确认 节是否写完
            if((i< ListCha1.size() && !ListCha1.get(i).sec.isWritten) || (i< ListCha2.size() && !ListCha2.get(i).sec.isWritten)) {
            	comTableRowNew = ComTable.createRow();
            	if(i< ListCha1.size() && !ListCha1.get(i).sec.isWritten) {

					XWPFParagraph pIO = comTableRowNew.getCell(0).addParagraph();
					XWPFRun rIO = pIO.createRun();
					rIO.setText(ListCha1.get(i).sec.toString());

//            		comTableRowNew.getCell(0).setText(ListCha1.get(i).sec.toString());
            		ListCha1.get(i).sec.isWritten = true;
            	}
            	if(i< ListCha2.size() && !ListCha2.get(i).sec.isWritten) {

					XWPFParagraph pIO = comTableRowNew.getCell(0).addParagraph();
					XWPFRun rIO = pIO.createRun();
					rIO.setText(ListCha2.get(i).sec.toString());

//            		comTableRowNew.getCell(1).setText(ListCha2.get(i).sec.toString());
            		ListCha2.get(i).sec.isWritten = true;
            	}
            }

            comTableRowNew = ComTable.createRow();
            if(i< ListCha1.size()) {

            	//
				String[] al = ListCha1.get(i).toString().split("\n");
				for(int p = 0; p <al.length; p++){
					XWPFParagraph pIO = comTableRowNew.getCell(0).addParagraph();
					XWPFRun rIO = pIO.createRun();
					rIO.setText(al[p]);
				}

//            	comTableRowNew.getCell(0).setText(ListCha1.get(i).toString());
            }else {
            	comTableRowNew.getCell(0).setText("");
            }
            
            if(i< ListCha2.size()) {

				String[] al = ListCha2.get(i).toString().split("\n");
				for(int p = 0; p <al.length; p++){
					XWPFParagraph pIO = comTableRowNew.getCell(1).addParagraph();
					XWPFRun rIO = pIO.createRun();
					rIO.setText(al[p]);
				}
//            	comTableRowNew.getCell(1).setText(ListCha2.get(i).toString());
            }else {
            	comTableRowNew.getCell(1).setText("");
            }
            
            
        }

    }

    public void NewWordCreate(List<ItemN> ListStr1,List<ItemN> listStr2,String path) throws IOException {
        //Blank Document

        XWPFDocument document= new XWPFDocument();
//		XWPFStyles xwpfStyles = document.createStyles();
//		xwpfStyles.addStyle(xwpfStyles);

        //Write the Document in file system
//        String OutPutPath = Resource
        FileOutputStream out = new FileOutputStream(new File(path + "result.docx")); // 下载路径/文件名称

        XWPFTable ComTable = document.createTable();

        //列宽自动分割

        CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();

        comTableWidth.setType(STTblWidth.DXA);

        comTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行

        createTable(ComTable, ListStr1, listStr2);


        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();

        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

        document.write(out);

        out.close();

    }
    
    public static void create(String path) throws Exception {
//      String[] a = "123".split("2");
		// 获取 文档信息
      String filePathOld = path + "compare1.doc";
      String content = POIServiceUtil.readWord(filePathOld);
      
      List<ItemN> lc_1 = textProduce(content);
      

      String filePathNew = path + "compare1.doc";
      String contentNew = POIServiceUtil.readWord(filePathNew);
      List<ItemN> lc_2 = textProduce(contentNew);
//
      WordExportController wc = new WordExportController();
      wc.NewWordCreate(lc_1,lc_2,path);
    }
    
    public static void main(String[] args)throws Exception {

    }


    public static void demo() throws IOException {
        //Blank Document

        XWPFDocument document= new XWPFDocument();

        //Write the Document in file system

        FileOutputStream out = new FileOutputStream(new File("create_table.docx")); // 下载路径/文件名称

        //工作经历表格

        XWPFTable ComTable = document.createTable();

        //列宽自动分割

        CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();

        comTableWidth.setType(STTblWidth.DXA);

        comTableWidth.setW(BigInteger.valueOf(9072));

        //表格第一行

        XWPFTableRow comTableRowOne = ComTable.getRow(0);

        comTableRowOne.getCell(0).setText("原法则");

        comTableRowOne.addNewTableCell().setText("新法则");

        //表格第二行

        XWPFTableRow comTableRowTwo = ComTable.createRow();

        comTableRowTwo.getCell(0).setText("2016-09-06");

        comTableRowTwo.getCell(1).setText("至今");

//        comTableRowTwo.getCell(2).setText("seawater");
//
//        comTableRowTwo.getCell(3).setText("123");

        //表格第三行

        XWPFTableRow comTableRowThree = ComTable.createRow();

        comTableRowThree.getCell(0).setText("2016-09-06");

        comTableRowThree.getCell(1).setText("至今");


        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();

        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);


        document.write(out);

        out.close();

        System.out.println("create_table document written success.");
    }
}
